﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraScheduler.UI;
using DevExpress.XtraScheduler;

namespace QLTV.Forms.KeHoach
{
    public partial class frmEditPlanPopup : BaseForm
    {
        SchedulerControl control;
        Appointment apt;
        bool openRecurrenceForm = false;
        int suspendUpdateCount;

        public int PlanID { get; set; }
        // The MyAppointmentFormController class is inherited from
        // the AppointmentFormController to add custom properties.
        // See its declaration below.
        MyAppointmentFormController controller;

        protected AppointmentStorage Appointments
        {
            get { return control.Storage.Appointments; }
        }

        protected bool IsUpdateSuspended { get { return suspendUpdateCount > 0; } }



        public frmEditPlanPopup(SchedulerControl control, Appointment apt, bool openRecurrenceForm)
        {
            this.openRecurrenceForm = openRecurrenceForm;
            this.controller = new MyAppointmentFormController(control, apt);
            this.apt = apt;
            this.control = control;
            //
            // Required for Windows Form Designer support
            //
            SuspendUpdate();
            InitializeComponent();
            ResumeUpdate();
            UpdateForm();
        }

        int Rankid;

        private void frmLongPopup_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'dsVessel.tblVesselGroup' table. You can move, or remove it, as needed.
            this.tblVesselGroupTableAdapter.Fill(this.dsVessel.tblVesselGroup);
            // TODO: This line of code loads data into the 'dsVessel.tblFlag' table. You can move, or remove it, as needed.
            this.tblFlagTableAdapter.Fill(this.dsVessel.tblFlag);
            int RankType = (int)control.SelectedResource.CustomFields["RankType"];
            int RankLevel = (int)control.SelectedResource.CustomFields["RankLevel"];
            Rankid = (int)control.SelectedResource.Id;
            int maxLevel = (int)tblRankTableAdapter.MaxLevel(RankType);
            if (RankLevel < maxLevel)
                RankLevel = RankLevel + 1;
            int RankLower = (int)tblRankTableAdapter.returnRankLower(RankType, RankLevel);

            // TODO: This line of code loads data into the 'dsLongPlan.tblRank' table. You can move, or remove it, as needed.
            this.tblRankTableAdapter.Fill(this.dsLongPlan.tblRank);
            // TODO: This line of code loads data into the 'dsLongPlan.tblCrew' table. You can move, or remove it, as needed.
            this.tblCrewTableAdapter.FillByRank(this.dsLongPlan.tblCrew, Rankid, RankLower);
            // TODO: This line of code loads data into the 'dsLongPlan.tblVessel' table. You can move, or remove it, as needed.
            this.tblVesselTableAdapter.Fill(this.dsLongPlan.tblVessel);

        }

        #region Save changes
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
        }
        #endregion


        #region khong can

        private void frmEditPlanPopup_Activated(object sender, EventArgs e)
        {
            if (openRecurrenceForm)
            {
                openRecurrenceForm = false;
                OnRecurrenceButton();
            }

        }

        private void OnRecurrenceButton()
        {
            ShowRecurrenceForm();
        }
        void ShowRecurrenceForm()
        {

            if (!control.SupportsRecurrence)
                return;

            // Prepare to edit the appointment's recurrence.
            Appointment editedAptCopy = controller.EditedAppointmentCopy;
            Appointment editedPattern = controller.EditedPattern;
            Appointment patternCopy = controller.PrepareToRecurrenceEdit();

            AppointmentRecurrenceForm dlg = new AppointmentRecurrenceForm(patternCopy, control.OptionsView.FirstDayOfWeek, controller);

            // Required for skin support.
            dlg.LookAndFeel.ParentLookAndFeel = this.LookAndFeel.ParentLookAndFeel;

            DialogResult result = dlg.ShowDialog(this);
            dlg.Dispose();

            if (result == DialogResult.Abort)
                controller.RemoveRecurrence();
            else
                if (result == DialogResult.OK)
                {
                    controller.ApplyRecurrence(patternCopy);
                    if (controller.EditedAppointmentCopy != editedAptCopy)
                        UpdateForm();
                }
            UpdateIntervalControls();
        }
        #endregion

        #region validate control and display
        private void dateStart_EditValueChanged(object sender, EventArgs e)
        {
            if (!IsUpdateSuspended)
                controller.DisplayStart = dateStart.DateTime.Date;
            UpdateIntervalControls();
        }

        private void dateEnd_EditValueChanged(object sender, EventArgs e)
        {
            if (IsUpdateSuspended) return;
            if (IsIntervalValid())
                controller.DisplayEnd = dateEnd.DateTime.Date;
            else
                dateEnd.EditValue = controller.DisplayEnd.Date;
        }
        bool IsIntervalValid()
        {
            DateTime start = dateStart.DateTime;
            DateTime end = dateEnd.DateTime;
            return end >= start;
        }

        void UpdateForm()
        {
            SuspendUpdate();
            try
            {
                //  edStatus.Status = Appointments.Statuses[controller.StatusId];
                // edLabel.Label = Appointments.Labels[controller.LabelId];

                dateStart.DateTime = controller.DisplayStart.Date;
                dateEnd.DateTime = controller.DisplayEnd.Date;
                lookupVessel.EditValue = controller.VesselID;
                lookupCrewName.EditValue = controller.CrewID;

            }
            finally
            {
                ResumeUpdate();
            }
            UpdateIntervalControls();
        }


        protected void SuspendUpdate()
        {
            suspendUpdateCount++;
        }

        protected void ResumeUpdate()
        {
            if (suspendUpdateCount > 0)
                suspendUpdateCount--;
        }

        #endregion

        #region display
        protected virtual void UpdateIntervalControls()
        {
            if (IsUpdateSuspended)
                return;

            SuspendUpdate();
            try
            {
                dateStart.EditValue = controller.DisplayStart.Date;
                dateEnd.EditValue = controller.DisplayEnd.Date;

                lookupCrewName.EditValue = controller.CrewID;
                lookupVessel.EditValue = controller.VesselID;

            }
            finally
            {
                ResumeUpdate();
            }
        }

        #endregion

        private void lookupCrewName_EditValueChanged(object sender, EventArgs e)
        {
            LookUpEdit lookup = sender as LookUpEdit;
            BindingManagerBase bm = BindingContext[lookup.Properties.DataSource];
            bm.Position = lookup.Properties.GetDataSourceRowIndex(lookup.Properties.ValueMember, lookup.EditValue);

        }
        string crewid = "";
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(crewid))
            {
                if (!controller.IsConflictResolved())
                    return;
                if (tblLongPlanVesselTableAdapter.CheckConflictCrew(this.dateStart.DateTime.Date, dateEnd.DateTime.Date, lookupCrewName.EditValue.ToString()).Rows.Count == 0)
                {
                    if (tblLongPlanVesselTableAdapter.CheckIfVacationMonthLessThan3(dateEnd.DateTime.Date, dateStart.DateTime.Date, lookupCrewName.EditValue.ToString()).Rows.Count != 0)
                    {
                        if (XtraMessageBox.Show(rm.GetString("sIfVacationMonthLessThan3", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo), MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                        {
                            controller.Subject = lookupCrewName.Text;
                            controller.Location = lookupVessel.Text;

                            controller.DisplayStart = this.dateStart.DateTime.Date;
                            controller.DisplayEnd = this.dateEnd.DateTime.Date;
                            controller.CrewID = (string)lookupCrewName.EditValue;
                            controller.VesselID = (int)lookupVessel.EditValue;
                            controller.PlanID = PlanID;
                            apt.ResourceIds.Add(Rankid);

                            // Save all changes of the editing appointment.
                            //controller
                            controller.ApplyChanges();
                            this.Close();
                        }
                        else
                            return;
                    }
                    else
                    {
                        controller.Subject = lookupCrewName.Text;
                        controller.Location = lookupVessel.Text;

                        controller.DisplayStart = this.dateStart.DateTime.Date;
                        controller.DisplayEnd = this.dateEnd.DateTime.Date;
                        controller.CrewID = (string)lookupCrewName.EditValue;
                        controller.VesselID = (int)lookupVessel.EditValue;
                        controller.PlanID = PlanID;
                        apt.ResourceIds.Add(Rankid);

                        // Save all changes of the editing appointment.
                        //controller
                        controller.ApplyChanges();
                        this.Close();
                    }
                }
                else
                {
                    XtraMessageBox.Show(rm.GetString("sConflict", myCultureInfo), rm.GetString("sMessageCaption", myCultureInfo));
                    return;
                }
            }

        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void viewCrew_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            if (viewCrew.FocusedRowHandle > -1)
            {
                
                crewid = viewCrew.GetFocusedRowCellValue("nCrewId").ToString();
            }
        }

        private void lookupVessel_EditValueChanged(object sender, EventArgs e)
        {
            LookUpEdit lookup = sender as LookUpEdit;
            BindingManagerBase bm = BindingContext[lookup.Properties.DataSource];
            bm.Position = lookup.Properties.GetDataSourceRowIndex("nVesselId", lookup.EditValue);
        }

    }


    #region Custom fields
    public class MyAppointmentFormController : AppointmentFormController
    {

        public int VesselID
        {
            get { return (int)EditedAppointmentCopy.CustomFields["VesselID"]; }
            set { EditedAppointmentCopy.CustomFields["VesselID"] = value; }
        }
        public string CrewID
        {
            get { return (string)EditedAppointmentCopy.CustomFields["CrewID"]; }
            set { EditedAppointmentCopy.CustomFields["CrewID"] = value; }
        }
        public int PlanID
        {
            get { return (int)EditedAppointmentCopy.CustomFields["PlanID"]; }
            set { EditedAppointmentCopy.CustomFields["PlanID"] = value; }
        }




        int SourceVesselID { get { return (int)SourceAppointment.CustomFields["VesselID"]; } set { SourceAppointment.CustomFields["VesselID"] = value; } }
        int SourcePlanID { get { return (int)SourceAppointment.CustomFields["PlanID"]; } set { SourceAppointment.CustomFields["PlanID"] = value; } }
        string SourceCrewID { get { return (string)SourceAppointment.CustomFields["CrewID"]; } set { SourceAppointment.CustomFields["CrewID"] = value; } }


        public MyAppointmentFormController(SchedulerControl control, Appointment apt)
            : base(control, apt)
        {
        }

        public override bool IsAppointmentChanged()
        {
            if (base.IsAppointmentChanged())
                return true;
            return SourceVesselID != VesselID ||
                SourceCrewID != CrewID || SourcePlanID != PlanID;
        }

        protected override void ApplyCustomFieldsValues()
        {
            SourceVesselID = VesselID;
            SourceCrewID = CrewID;
            SourcePlanID = PlanID;
        }
    }
    #endregion
}